﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

using BOSS.Service.Caching;

namespace BOSS.Service.Implements.Caching
{
    /// <summary>
    /// 基于 ASP.Net Cache 的分类缓存实现
    /// </summary>
    /// <typeparam name="TKey"></typeparam>
    /// <typeparam name="TValue"></typeparam>
    public class AspNetCategoryCache<TKey, TValue> : ICategoryCache<TKey, TValue>
    {
        /// <summary>
        /// 获取 分类缓存名称
        /// </summary>
        public string Name { get; private set; }

        /// <summary>
        /// 前缀
        /// </summary>
        private string m_prefix;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="name"></param>
        public AspNetCategoryCache(string name)
        {
            this.Name = name;
            this.m_prefix = name + "_";
        }

        #region ICategoryCache<TKey,TValue> 成员

        /// <summary>
        /// 添加缓存内容
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public void Add(TKey key, TValue value)
        {
            HttpRuntime.Cache[this.m_prefix + key] = value;
        }

        /// <summary>
        /// 获取缓存的内容
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public TValue Get(TKey key)
        {
            object value = HttpRuntime.Cache[this.m_prefix + key];
            if (value is TValue)
            {
                return (TValue)value;
            }
            return default(TValue);
        }

        /// <summary>
        /// 清除指定的缓存内容
        /// </summary>
        /// <param name="key"></param>
        public void Remove(TKey key)
        {
            HttpRuntime.Cache.Remove(this.m_prefix + key);
        }

        /// <summary>
        /// 清除整个分类缓存
        /// </summary>
        public void Clear()
        {
            IList<object> shouldBeRemove = new List<object>();

            IDictionaryEnumerator de = HttpRuntime.Cache.GetEnumerator();
            while (de.MoveNext())
            {
                string key = de.Key.ToString();
                if (key.StartsWith(this.m_prefix))
                {
                    shouldBeRemove.Add(key);
                }
            }

            foreach (string key in shouldBeRemove)
            {
                HttpRuntime.Cache.Remove(key);
            }
        }

        #endregion
    }
}
